package com.sugon.webservice.service.impl;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.sugon.webservice.entity.BatchDataAcessCmd;
import com.sugon.webservice.entity.ExternalTabRelationEntity;
import com.sugon.webservice.entity.Result;
import com.sugon.webservice.service.INwService;
import com.sugon.webservice.service.XyData2Service;
import com.sugon.webservice.service.XyDataService;
import lombok.extern.slf4j.Slf4j;
//import lombok.var;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.jws.WebMethod;
import javax.jws.WebService;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import static cn.hutool.json.XML.toJSONObject;

/**
 * @auther: duke
 * @description:
 * @date: 14:06 2022/12/29
 */
@Slf4j
@WebService(name = "DataAccess", targetNamespace = "http://tempuri.org/", endpointInterface = "com.sugon.webservice.service.INwService")
public class NwServiceImpl implements INwService {
    @Value("${nw.service}")
    String nwServiceUrl;

    @Value("${xy.service}")
    String xyServiceUrl;

    @Value("${xy.workspaceId}")
    String xyWorkSpaceId;

    @Value("${xy.account}")
    String xyAccount;

    @Autowired
    private XyDataService xyDataService;
    @Autowired
    private XyData2Service xyDataService2;
    @Override
    public String LoginByAccount(String userid, String password) {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(nwServiceUrl);
        try {
            return client.invoke("LoginByAccount", userid, password)[0].toString();
        } catch (Exception e) {
            log.error(e.getMessage());
            return getException(e.getMessage());
        }
    }

    @Override
    public String pushXml(String guid, String catalogid, String xmlstr) {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(nwServiceUrl);
        try {
            Object[] remoteObjects = client.invoke("pushXml", guid, catalogid, xmlstr);
            String msg = remoteObjects[0].toString();
            if (msg.contains("推送成功")) {
                //解析xmlstr并推送到轩辕
              String res =  dataAccessBatch(xmlstr,catalogid);
                if (res.contains("成功")){
                    return msg;
                }else {
                    return res;
                }
            }
            return msg;
        } catch (Exception e) {
            log.error(e.getMessage());
            return getException(e.getMessage());
        }
    }

    @WebMethod(exclude=true)
    @Override
    public String pushXmlBackflow(String guid, String catalogid, String xmlstr) {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(nwServiceUrl);
        try {
            Object[] remoteObjects = client.invoke("pushXmlBackflow", guid, catalogid, xmlstr);
            String msg = remoteObjects[0].toString();
            return msg;
        } catch (Exception e) {
            log.error(e.getMessage());
            return getException(e.getMessage());
        }
    }

    private String getException(String exception) {
        Document document = XmlUtil.createXml("Response");
        Element response = document.getDocumentElement();
        Element flag = XmlUtil.appendChild(response, "flag");
        flag.setTextContent("false");
        Element msg = XmlUtil.appendChild(response, "msg");
        msg.setTextContent(exception);
        return XmlUtil.toStr(document);
    }

    private String dataAccessBatch(String xmlstr,String catalogid) {
        Result<ExternalTabRelationEntity> externalTabRelationEntityResult = xyDataService.detail2(catalogid);
        String tabId = externalTabRelationEntityResult.getData().getTabId();
//        System.out.println(tabId);
//        String tabId = "d253b9328e2b4eebbdd6be8a33ba3e58";
//        String workspaceId = "274";
//        String account = "admin";
        List bodyData = update(xmlstr);
        BatchDataAcessCmd batchDataAcessCmd = new BatchDataAcessCmd();
        batchDataAcessCmd.setJsonStrs(bodyData);
        batchDataAcessCmd.setTabId(tabId);
        Result<String> stringResult = xyDataService2.dataAcessBatch(batchDataAcessCmd);
//        Console.log(JSONUtil.toJsonStr(new JSONObject() {{
//            putOpt("tabId", tabId);
//            putOpt("jsonStrs", bodyData);
//        }}));
        String res = stringResult.getMsg();
//        String res = HttpRequest.post(xyServiceUrl)
//                .header("workspaceId", xyWorkSpaceId)
//                .header("account", xyAccount)
//                .header("Content-Type", "application/json")
//                .body(JSONUtil.toJsonStr(new JSONObject() {{
//                    putOpt("tabId", tabId);
//                    putOpt("jsonStrs", bodyData);
//                }}))
//                .execute()
//                .body();
//        Console.log(res);//        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        if (!res.contains("成功")){
           return getException(res);
        }
        return res;
    }

    private ArrayList update(String xmlstr) {

        JSONObject jsonObject1 = toJSONObject(xmlstr);
        JSONObject table = (JSONObject) jsonObject1.get("table");
        JSONArray D1 = null;
        JSONObject D2 = null;
        try {
            D1 = (JSONArray) table.get("row");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            D2 = (JSONObject) table.get("row");
        } catch (Exception e) {
            e.printStackTrace();
        }

        ArrayList<String> list1 = new ArrayList();//存key
        ArrayList s = new ArrayList();//存所有

        if (D2 != null && D1 == null) {
            Set<String> strings = D2.keySet();
            Iterator<String> it = strings.iterator();
            while (it.hasNext()) {
                list1.add(it.next());
            }
            System.out.println(list1);
        } else {
            JSONObject o = (JSONObject) D1.get(0);
            Set<String> strings = o.keySet();
            Iterator<String> it = strings.iterator();
            while (it.hasNext()) {
                list1.add(it.next());
            }
        }

        if (D2 != null && D1 == null) {
            JSONObject jsonObject = new JSONObject();
            int j = 0;
            while (++j < list1.size()) {
                JSONObject value = (JSONObject) D2.get(list1.get(j));
                jsonObject.put(list1.get(j), value.get("content"));
            }
            s.add(jsonObject);
        } else {
//            for (int i = 0; i < D1.size(); i++) {
//                JSONObject jsonObject = new JSONObject();
//                int j = 0;
//                while (++j < list1.size()) {
//                    JSONObject o = (JSONObject) D1.get(i);
//                    JSONObject value = (JSONObject) o.get(list1.get(j));
//                    jsonObject.put(list1.get(j), value.get("content"));
//                }
//                s.add(jsonObject);
//            }
            D1.stream().forEach(
                    item->{
                        JSONObject jsonObject = new JSONObject();
                        int j = 0;
                        while (++j < list1.size()) {
                            JSONObject o = (JSONObject) item;
                            JSONObject value = (JSONObject) o.get(list1.get(j));
                            jsonObject.put(list1.get(j), value.get("content"));
                        }
                        s.add(jsonObject);
                    }
            );
        }

        ArrayList bodyData = new ArrayList();
        s.stream().forEach(field -> {
            String data_json = JSON.toJSONString(field);
            bodyData.add(data_json);
        });

      return bodyData;

    }
}
